﻿using System;
using System.Data;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;
using System.Collections.Generic;
using System.IO;
using System.Drawing;
using HRM.Utilities;
using HRM.BusinessLogic;
namespace HRM
{
    public partial class frmMauEpChucDanh : FormBase
    {
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        String department_Id = "0";
        int branch_ID = 0;
        bool cboMonthFirstLoad = true;
        RoleRightInfo listRole;
        public DataTable dtNhanSu;
        private Int32 type = 1;
        public override void Show_Form()
        {
            this.Show();
        }

        public frmMauEpChucDanh()
        {
            InitializeComponent();
            listRole = UIParamater.Quyen_CanhBaoSapSinhNhat;
            this.KeyPreview = true;
            //
            Init_Control();
        }

        protected override void Init_Control()
        {
            LoadLanguage();
            Init_Grid();
            ComboboxItem cbItem;
            cboYear.ComboBox.DisplayMember = "Text";
            cboYear.ComboBox.ValueMember = "Value";
            cbItem = new ComboboxItem("Tất cả", 0);
            cboYear.ComboBox.Items.Add(cbItem);
            for (int year = DateTime.Now.Year; year >= 2008; year--)
            {
                cbItem = new ComboboxItem(year.ToString(), year);
                cboYear.ComboBox.Items.Add(cbItem);
                //if (year == DateTime.Now.Year)
                //    cboYear.ComboBox.SelectedItem = cbItem;
            }
            cboYear.SelectedIndex = 0;
            cboMonthFirstLoad = false;
            FormGlobals.Control_SetVisible(false, lstEmployee);
            LoadData(type);
        }

        void LoadLanguage()
        {
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }

        DataGridHandle m_GridHandle;
        DataGridHandle m_GridHandle_History;
        protected void Init_Grid()
        {
            dgvList.Columns.Clear();
            //      
            dgvList.Columns.AddRange(
                FormGlobals.Grid_NewColumn<DataGridViewCheckBoxColumn>("Chọn", "Chon", 90),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "HOTEN", 150),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BHXH", "SOBHXH", 100),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày sinh", "NGAYSINH", 90, Globals.CS_DISPLAY_DATE_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mã C/vụ", "MACV", 300),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Từ tháng", "TUTHANG", 80, Globals.CS_EDIT_MONTHYEAR_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Đến tháng", "DENTHANG", 80, Globals.CS_EDIT_MONTHYEAR_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mã phòng ban", "MAPB", 160));
            m_GridHandle = FormGlobals.Grid_Init(dgvList, "");
            //
            dgvHistory.Columns.AddRange(
                FormGlobals.Grid_NewColumn<DataGridViewCheckBoxColumn>("Chọn", "Chon", 90),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Họ và tên", "HOTEN", 150),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Số sổ BHXH", "SOBHXH", 100),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Ngày sinh", "NGAYSINH", 90, Globals.CS_DISPLAY_DATE_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mã C/vụ", "MACV", 300),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Từ tháng", "TUTHANG", 80, Globals.CS_EDIT_MONTHYEAR_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Đến tháng", "DENTHANG", 80, Globals.CS_EDIT_MONTHYEAR_FORMAT),
                FormGlobals.Grid_NewColumn<DataGridViewTextBoxColumn>("Mã phòng ban", "MAPB", 160));
            m_GridHandle_History = FormGlobals.Grid_Init(dgvHistory, "");
            //
            dgvList.CellClick += new DataGridViewCellEventHandler(dgvList_CellClick);
            dgvHistory.CellClick += new DataGridViewCellEventHandler(dgvHistory_CellClick);
            //
            txtDepartment_Code.TextChanged += new EventHandler(txtDepartment_Code_TextChanged);
            txtDepartment_Code.KeyDown += new KeyEventHandler(txtDepartment_Code_KeyDown);
            txtDepartment_Code.Enter += new EventHandler(txtDepartment_Code_Enter);
            lstEmployee.MouseDoubleClick += new MouseEventHandler(lstEmployee_MouseDoubleClick);
            lstEmployee.KeyDown += new KeyEventHandler(lstEmployee_KeyDown);
            btnUpdate.Click += new EventHandler(btnUpdate_Click);
            btnDelete.Click += new EventHandler(btnDelete_Click);
        }

        void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                if (type > 0)
                {
                    DataTable dt = dtNhanSu.GetChanges(DataRowState.Modified);
                    if (dt != null)
                    {
                        Int32 countChon = Int32.Parse(dt.Compute("COUNT(Chon)", "Chon=1").ToString());
                        if (countChon > 0)
                        {
                            FormGlobals.App_ProgressSave(delegate()
                            {
                                foreach (DataRow drow in dt.Rows)
                                {
                                    if (Int32.Parse(drow["Chon"].ToString()) > 0)
                                        Employee_Controller.Instance().Employee_DeleteChucDanh(Int32.Parse(drow["Detail_Id"].ToString()));
                                }
                            });
                            LoadData(type);
                        }
                        else
                        {
                            FormGlobals.Message_Warning("Chưa tích chọn dòng nào");
                            return;
                        }
                    }
                }
                else
                {
                    FormGlobals.Message_Warning("Chỉ được xóa với chức danh mới");
                    return;
                }
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Error(ex);
            }
        }

        void btnUpdate_Click(object sender, EventArgs e)
        {
            DataTable dt = dtNhanSu.GetChanges(DataRowState.Modified);
            if (dt != null)
            {
                Int32 countChon = Int32.Parse(dt.Compute("COUNT(Chon)", "Chon=1").ToString());
                if (countChon > 0)
                {
                    if (new frmMauepChucDanh_Edit().Show_Form(dt) == DialogResult.OK)
                    {
                        LoadData(type);
                    }
                }
                else
                {
                    FormGlobals.Message_Warning("Chưa tích chọn dòng nào");
                    return;
                }
            }
            else
            {
                FormGlobals.Message_Warning("Chưa tích chọn dòng nào");
                return;
            }
        }

        void dgvList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvList.Columns["Chon"].Index)
            {
                DataRow dr = m_GridHandle.GetRowData(e.RowIndex);
                if (dr != null)
                {
                    if (Int32.Parse(dr["Chon"].ToString()) > 0)
                        dr["Chon"] = false;
                    else
                        dr["Chon"] = true;
                }
            }
        }
        void dgvHistory_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dgvList.Columns["Chon"].Index)
            {
                DataRow dr = m_GridHandle_History.GetRowData(e.RowIndex);
                if (dr != null)
                {
                    if (Int32.Parse(dr["Chon"].ToString()) > 0)
                        dr["Chon"] = false;
                    else
                        dr["Chon"] = true;
                }
            }
        }
        void txtDepartment_Code_Enter(object sender, EventArgs e)
        {
            txtDepartment_Code.SelectAll();
        }

        private void txtDepartment_Code_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down)
            {
                if (lstEmployee.Items.Count > 0)
                {
                    lstEmployee.Focus();
                    for (int i = 0; i < lstEmployee.Items.Count; i++)
                    {
                        if (lstEmployee.Items[i].Selected)
                        {
                            txtDepartment_Code.Text = lstEmployee.Items[i].SubItems[1].Text;
                            department_Id = lstEmployee.Items[i].SubItems[0].Name;
                        }
                    }

                }
            }
            else if (e.KeyCode == Keys.Right && (txtDepartment_Code.SelectionLength == txtDepartment_Code.Text.Length || txtDepartment_Code.SelectionStart == txtDepartment_Code.Text.Length))
            {
                this.ProcessTabKey(true);
                ((TextBox)sender).SelectAll();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Left && (txtDepartment_Code.SelectionLength == txtDepartment_Code.Text.Length || txtDepartment_Code.SelectionStart == 0))
            {
                this.ProcessTabKey(false);
                ((TextBox)sender).SelectAll();
                e.Handled = true;
            }
            else if (e.KeyCode == Keys.Enter)
            {
                if (lstEmployee.Items.Count == 1 && lstEmployee.Visible)
                {
                    txtDepartment_Code.Text = lstEmployee.Items[0].SubItems[1].Text;
                    department_Id = lstEmployee.Items[0].SubItems[0].Name;
                    txtDepartment_Code.SelectAll();
                    lstEmployee.Visible = false;
                }
            }
        }

        void lstEmployee_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (lstEmployee.Items.Count > 0)
                {
                    for (int i = 0; i < lstEmployee.Items.Count; i++)
                    {
                        if (lstEmployee.Items[i].Selected)
                        {
                            lstEmployee.Items[i].BackColor = Color.Yellow;
                            txtDepartment_Code.Text = lstEmployee.Items[i].SubItems[1].Text;
                            department_Id = lstEmployee.Items[i].SubItems[0].Name;

                        }
                    }
                }
                lstEmployee.SendToBack();
                txtDepartment_Code.Focus();
                lstEmployee.Visible = false;
                if (txtDepartment_Code.Text != Convert.ToString(txtDepartment_Code.Tag) && Convert.ToString(txtDepartment_Code.Tag) != "")
                {
                    this.ProcessTabKey(true);
                    this.ProcessTabKey(true);
                    this.ProcessTabKey(true);
                    this.ProcessTabKey(true);
                }
            }
        }
        void lstEmployee_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            for (int i = 0; i < lstEmployee.Items.Count; i++)
            {
                if (lstEmployee.Items[i].Selected)
                {
                    txtDepartment_Code.Text = lstEmployee.Items[i].SubItems[1].Text;
                    department_Id = lstEmployee.Items[i].SubItems[0].Name;
                }
            }
            lstEmployee.SendToBack();
            txtDepartment_Code.Focus();
            lstEmployee.Visible = false;
        }

        //Tự động hiển thị danh sách phòng ban
        void AutoCompleteEmployee(string Parameter)
        {
            lstEmployee.Items.Clear();
            DataTable dtDepart = LocalDB.Department_GetListByParameter(Parameter);
            ListViewItem item;
            if (dtDepart != null)
                for (int i = 0; i < dtDepart.Rows.Count; i++)
                {
                    item = new ListViewItem(dtDepart.Rows[i]["Department_Code"].ToString());
                    item.SubItems.Add(dtDepart.Rows[i]["Department_Name"].ToString());
                    item.Name = dtDepart.Rows[i]["Department_Id"].ToString();
                    //Chỉ hiển thị danh sách nhân sự thuộc branch hiện tại
                    if (Convert.ToInt32(dtDepart.Rows[i]["Department_BranchID"]) == Program.intBranchID)
                        lstEmployee.Items.Add(item);
                }
        }

        void txtDepartment_Code_TextChanged(object sender, EventArgs e)
        {
            if (txtDepartment_Code.Focused)
            {
                if (txtDepartment_Code.Text.Length > 0)
                {
                    AutoCompleteEmployee(txtDepartment_Code.Text);
                    if (lstEmployee.Items.Count > 0)
                    {
                        lstEmployee.Visible = true;
                        lstEmployee.HeaderStyle = ColumnHeaderStyle.None;
                        lstEmployee.BringToFront();
                        lstEmployee.Items[0].Selected = true;
                    }
                    else
                    {
                        lstEmployee.Visible = false;
                        department_Id = "0";
                    }
                }
                else
                {
                    lstEmployee.Visible = false;
                    department_Id = "0";
                }


            }
        }
        private DataTable dtChucDanh;
        //Lấy danh sách quá trình chức danh theo năm
        private void LoadData(Int32 type)
        {
            try
            {
                int _year = (int)((ComboboxItem)cboYear.ComboBox.SelectedItem).Value;
                FormGlobals.App_ProgressShow(delegate()
                {
                    dtChucDanh = Employee_Controller.Instance().Employee_DSChuDanh(
                        Program.strBranchCode
                        , Int32.Parse(department_Id)
                        , ""
                        , _year
                        , type);
                    //
                    dtChucDanh.Columns.Add(new DataColumn("RowId", typeof(String)));
                    dtNhanSu = dtChucDanh.Clone();
                    DataColumn[] keys = new DataColumn[2];
                    keys[0] = dtNhanSu.Columns["SOBHXH"];
                    keys[1] = dtNhanSu.Columns["MACV"];
                    dtNhanSu.PrimaryKey = keys;
                    foreach (DataRow drow in dtChucDanh.Rows)
                    {
                        String macv = Globals.DB_GetValue<String>(drow["MACV"], "Chưa xác định");
                        DataRow row = dtNhanSu.Rows.Find(new Object[] { drow["SOBHXH"].ToString(), macv });
                        if (row == null)
                        {
                            row = dtNhanSu.NewRow();
                            foreach (DataColumn col in dtNhanSu.Columns)
                                row[col.ColumnName] = drow[col.ColumnName];
                            row["RowId"] = drow["Detail_Id"];
                            row["MACV"] = macv;
                            dtNhanSu.Rows.Add(row);
                        }
                        else
                        {
                            row["DENTHANG"] = drow["DENTHANG"];
                            row["RowId"] = row["RowId"].ToString() + "," + drow["Detail_Id"].ToString();
                        }
                    }
                    dtChucDanh.AcceptChanges();
                    dtNhanSu.AcceptChanges();
                }, "Lấy danh sách chức danh", "Hoàn thành!");
                //PageIndex();
                //            
                dgvList.DataSource = dtNhanSu;
                dgvHistory.DataSource = dtNhanSu;
            }
            catch (Exception ex)
            {
                FormGlobals.Message_Error(ex);
            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            //string _month = cboMonth.Text;
            //string _ReportText = "sinhnhattrongthang";
            //frmPreviewReport f = new frmPreviewReport("Birth day in month", new string[] { _ReportText, _month, branch_ID.ToString(), department_ID.ToString() });
            //f.Show(this);
        }

        private void btnWarning_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData(type);
        }
        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            currPage = 0;
            //if(!cboMonthFirstLoad)
            LoadData(type);
        }

        private void frmBirthDayList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
        }

        private void frmBirthDayList_FormClosing(object sender, FormClosingEventArgs e)
        {
            //wcfEmployee.Close();
            //wcfMain.Close();
        }

        private void toolStripButton2_Click(object sender, EventArgs e)
        {
            string fileName = "MauEpChucDanh.xls";
            try
            {
                if (dtNhanSu.Rows.Count > 0)
                {
                    DataTable dt = dtNhanSu.Copy();
                    dt.Columns.Remove("ISNEW");
                    dt.Columns.Remove("Detail_Id");
                    dt.Columns.Remove("RowId");
                    UnicodeConvert.UnicodeToTCVN3(ref dt);
                    ReadExcelFile.exportDataToExcel(dt, Path.GetTempPath() + "\\" + fileName);
                    try
                    {
                        System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + fileName);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + fileName, "Thông báo");
                    }
                }
                else
                    Program.taskbarNotifier.Show(UpdateUI.GetString("thongbao"), "Không có dữ liệu!", UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
            }
            catch (Exception ex)
            {
                MessageBox.Show("File " + Path.GetTempPath() + "\\" + fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadData(type);
        }

        private void tabChucDanh_TabIndexChanged(object sender, EventArgs e)
        {
            if (tabChucDanh.SelectedTab == tbpChucDanh_New)
                type = 1;
            else
                type = 0;
            LoadData(type);
        }

        private void ckbCheckAll_CheckedChanged(object sender, EventArgs e)
        {
            bool check = false;
            if (ckbCheckAll.Checked)
                check = true;
            foreach (DataRow dr in dtNhanSu.Rows)
            {
                dr["Chon"] = check;
            }
        }
    }
}
